package com.zx.tv.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.zx.base.ctrl.Constant;
import com.zx.base.ctrl.KeyTable;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.URLHelper;
import com.zx.base.lazylist.ImageLoader;
import com.zx.base.util.DPIExchange;
import com.zx.base.widget.MyGallery;
import com.zx.tv.R;
import com.zx.tv.adapter.NewListImgAdapter;
import com.zx.tv.app.NewTVApp;
import com.zx.tv.entity.NewListPic;

public class NewList extends Activity {

	private MyGallery gallery;
	private ArrayList<NewListPic> newsPicList = new ArrayList<NewListPic>();
	private ImageLoader imageLoader;
	private NewListImgAdapter listImage;
	private ImageView newslist_adv_0, newslist_adv_1;
	private ImageView img;
	private ViewFlipper newslist_flipper;
	private TextView newslist_weather_1, newslist_weather_2,
			newslist_weather_3,news_content_text;
	private String listId;
	private RelativeLayout top, bottom, substance;
	
	private boolean  mOnTouch = false;
	private int mPosition = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newslist);

		top = (RelativeLayout) findViewById(R.id.top);
		bottom = (RelativeLayout) findViewById(R.id.bottom);
		substance = (RelativeLayout) findViewById(R.id.substance);
		newslist_flipper = (ViewFlipper) findViewById(R.id.newslist_flipper);
		newslist_adv_0 = (ImageView) findViewById(R.id.newslist_adv_0);
		newslist_adv_1 = (ImageView) findViewById(R.id.newslist_adv_1);
		gallery = (MyGallery) findViewById(R.id.news_gallery);
		DPIExchange dpi = new DPIExchange(this);
		LayoutParams toplp = new LayoutParams(LayoutParams.MATCH_PARENT,
				dpi.heightChange(100));
		top.setLayoutParams(toplp);

		LayoutParams flipperlp = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		flipperlp.setMargins(dpi.widthChange(375), 0, dpi.widthChange(375), 0);
		newslist_flipper.setLayoutParams(flipperlp);

		LayoutParams headerlp = new LayoutParams(LayoutParams.MATCH_PARENT,
				dpi.heightChange(100));
		headerlp.setMargins(dpi.widthChange(375), 0, dpi.widthChange(375), 0);
		LayoutParams bottomlp = new LayoutParams(LayoutParams.MATCH_PARENT,
				dpi.heightChange(100));
		bottomlp.alignWithParent = true;
		bottomlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		bottom.setLayoutParams(bottomlp);
		LayoutParams rp = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		rp.setMargins(dpi.widthChange(375), dpi.heightChange(200),
				dpi.widthChange(375), dpi.heightChange(200));
		substance.setLayoutParams(rp);
		LayoutParams advl =  new LayoutParams(dpi.widthChange(200),
				dpi.heightChange(680));
		advl.setMargins(20, dpi.heightChange(200), 0, 0);
		advl.alignWithParent = true;
		advl.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		newslist_adv_0.setLayoutParams(advl);
		LayoutParams advr = new LayoutParams(dpi.widthChange(200),
				dpi.heightChange(680));
		advr.setMargins(0, dpi.heightChange(200),20, 0);
		advr.alignWithParent = true;
		advr.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		newslist_adv_1.setLayoutParams(advr);
		
		imageLoader = ((NewTVApp) getApplication()).imageloader;
		listId = getIntent().getStringExtra("listId");
		img = (ImageView) findViewById(R.id.news_icon);

		newslist_weather_1 = (TextView) findViewById(R.id.newslist_weather_1);
		newslist_weather_2 = (TextView) findViewById(R.id.newslist_weather_2);
		newslist_weather_3 = (TextView) findViewById(R.id.newslist_weather_3);

		newslist_flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_up_in));
		newslist_flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_up_out));
		newslist_flipper.startFlipping();

		listImage = new NewListImgAdapter(this, newsPicList, imageLoader);
		news_content_text=(TextView)findViewById(R.id.news_content_text);
//		img.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// 跳到图片放大
//
//				Intent intent = new Intent(NewList.this, Detail.class);
//				startActivity(intent);
//
//			}
//		});
		gallery.setAdapter(listImage);
		gallery.setSelection(3);// 默认选择第二个
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				if(0 == newsPicList.size()){
					
				}else{
					NewListPic info = newsPicList.get(position%newsPicList.size());
					imageLoader.DisplayImage(
							URLHelper.mPrefixImg + info.getImg_url(), img,
							R.drawable.loading);
					news_content_text.setText(Html.fromHtml(info.getContent()));
				}
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}

		});
		gallery.setOnItemClickListener(new OnItemClickListener() {
            //用户点击图片时，将该图片的ResourceID设到下面的ImageView中去，
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position,
                    long arg3) { 
				
            	Intent intent = new Intent(NewList.this, NewsContent.class);
            	intent.putExtra("contentid", newsPicList.get(position%newsPicList.size()).getId());
				startActivity(intent);
                
            }
        });
		
		new InfoTask().execute(URLHelper.mPrefix);
		
		startAutoScroll();
	}

	class InfoTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			Map<String, String> map = new HashMap<String, String>();
			map.put("act", "newsList");
			map.put("type", listId);
			return HttpUtils.readHttp(params[0], map);// 网络操作，向服务器发送登录请求，获取返回信息

		}

		@Override
		protected void onPostExecute(String result) {

			if (Constant.debug)
				Log.d("TAG", "login result = " + result);
			if (result == null || result.equals("timeout") || result == "") {
				Toast toast = Toast.makeText(NewList.this, "网络超时。",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			} else {
				// 发送解析数据 消息
				parseJson(result);
			}

		}
	}

	// 解析获取的服务器json数据
	private void parseJson(String str) {
		try {
			JSONObject result = new JSONObject(str);
			String succeed = result.getString("succeed");
			if (succeed.equals("000")) {
				JSONArray datalist = result.getJSONArray("dataList");
				for (int i = 0; i < datalist.length(); i++) {
					JSONObject one = datalist.getJSONObject(i);
					NewListPic np = new NewListPic();
					np.setId(one.getString("id"));
					np.setTitle(one.getString("title"));
					np.setAuthor(one.getString("author"));
					np.setContent(one.getString("content"));
					np.setImg_url(one.getString("imgurl"));
					np.setSource(one.getString("source"));
					np.setSubhead(one.getString("subhead"));
					np.setType(one.getString("type"));
					np.setPtime(one.getString("ptime"));
					newsPicList.add(np);
				}

				listImage.notifyDataSetChanged();
				gallery.setSelection(4);// 默认选择第二个
				JSONArray advertisList = result.getJSONArray("advList");
				for (int i = 0; i < advertisList.length(); i++) {
					JSONObject one = advertisList.getJSONObject(i);
					int position = one.getInt("position");
					switch (position) {
					case 0:
						imageLoader.DisplayImage(
								URLHelper.mPrefixImg + one.getString("imgurl"),
								newslist_adv_0, R.drawable.loading);
						break;
					case 1:
						imageLoader.DisplayImage(
								URLHelper.mPrefixImg + one.getString("imgurl"),
								newslist_adv_1, R.drawable.loading);
						break;

					default:
						break;
					}
				}
				JSONObject weather = result.getJSONObject("weather");
				newslist_weather_1.setText(Html.fromHtml(weather.getJSONObject(
						"weather1").getString("msg")));
				newslist_weather_2.setText(Html.fromHtml(weather.getJSONObject(
						"weather2").getString("msg")));
				newslist_weather_3.setText(Html.fromHtml(weather.getJSONObject(
						"weather3").getString("msg")));

			} else {

			}
		} catch (Exception e) {
			Log.d("TAG", "" + e.toString());
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// if (keyCode == KeyTable.KEY_ENTER) {
//		Intent intent = new Intent(NewList.this, NewsContent.class);
//		// intent.putExtra("listId","1");
//		startActivity(intent);
		// return true;
		// }
		if(keyCode == KeyTable.KEY_LEFT || keyCode == KeyTable.KEY_RIGHT){
			 mOnTouch = true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void startAutoScroll() {
        new Thread() {
            @Override
            public void run() {
                int count = 0;  
                while (true) {
                    count= 0;
                    //这段逻辑用于用户手动滑动时，停止自动滚动
                    while (count < 30) {
                        count++;
                        try {
                            Thread.sleep(100);
                        }catch(InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (mOnTouch) {// 用戶手动滑动时，停止自动滚动
                            count= 0;
                        }
                    }   
                    mPosition++;
                    Message msg = mHandler.obtainMessage(99, mPosition, 0);
                    mHandler.sendMessage(msg);
                }
            }
        }.start();
    }
	private Handler mHandler= new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 99:
            	gallery.setSelection(msg.arg1);//进行图片切换
                break;
            }
        }
    };

}